package com.gitee.huxing.course.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.huxing.course.config.exception.ServiceException;
import com.gitee.huxing.course.domain.mapper.PlatFormOrderMapper;
import com.gitee.huxing.course.domain.module.PlatFormOrderDO;
import com.gitee.huxing.course.domain.service.OrderService;
import com.gitee.huxing.course.service.PlatFormOrderService;
import com.gitee.huxing.framework.redis.MessagePublisher;
import com.gitee.huxing.framework.redis.RedisMessagePublisher;
import com.gitee.huxing.framework.redis.RedisUtils;
import com.gitee.huxing.framework.redis.RedisWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.service.impl
 * @ClassName: PlatFormOrderServiceImpl
 * @Author: huxing
 * @DateTime: 2021-09-17 下午5:37
 */
@Slf4j
@Service
public class PlatFormOrderServiceImpl implements PlatFormOrderService {

    @Autowired
    OrderService orderService;

    @Resource
    MessagePublisher redisMessagePublisher;

    @Resource
    RedisWrapper redisWrapper;

    @Override
    public PlatFormOrderDO purchase() throws ServiceException {
        // 生成支付订单
        PlatFormOrderDO orderDO = PlatFormOrderDO.createBuilderTest();
        int count = redisWrapper.getInt(orderDO.getProductId());
        log.info("当前库存数量: {}", count);
        if (count <= 0){
            log.info("库存数量不足, 需要重新添加库存");
            throw new ServiceException("下单失败，库存数量不足");
        }
        // 写入订单记录
        orderDO = this.orderService.insert(orderDO);
        // 订单插入消息处理
        redisMessagePublisher.publish(JSONObject.toJSONString(orderDO));
        // 返回订单记录
        return orderDO;
    }

    @Override
    public PlatFormOrderDO updateOrder(String orderId) throws ServiceException {
        // 修改订单记录
        PlatFormOrderDO orderDO = PlatFormOrderDO.paymentOrderTest(orderId);
        Assert.isNull(orderId, "订单号记录不能为空");
        // 查询并返回修改后的订单记录
        return this.orderService.update(orderDO);
    }

    @Override
    public PlatFormOrderDO queryOrder(String orderId) throws ServiceException {
        // TODO: 查询订单记录
        return this.orderService.getOrderById(orderId);
    }

    @Override
    public void deleteOrder(String orderId) throws ServiceException {
        // 根据订单号删除订单记录
        this.orderService.delete(orderId);
    }
}
